﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Eqwww.Domain.Models.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Eqwww.App.SystemManage;
using Microsoft.EntityFrameworkCore.Storage;
using System.Security.Claims;
using Eqwww.App.Identity;
using Eqwww.Code;

namespace Eqwww.Web.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class LogoutModel : PageModel
    {
        private UserApp _userApp;
        private readonly SignInManager<UserModel> _signInManager;
        private readonly ILogger<LogoutModel> _logger;
        private DatabaseLogApp _databaseLogApp;

        public LogoutModel(SignInManager<UserModel> signInManager, ILogger<LogoutModel> logger,
            DatabaseLogApp databaseLogApp,
            UserApp userApp)
        {
            _signInManager = signInManager;
            _logger = logger;
            _databaseLogApp = databaseLogApp;
            _userApp = userApp;
        }

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPost(string returnUrl = null)
        {
            var user = await _userApp.GetUserAsync(User);
            //var principal = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
            await _signInManager.SignOutAsync();
            _databaseLogApp.LogInformationLogout(user);
            _logger.LogInformation("User logged out.");
            return Content(Common.SuccessResult().ToJson());
        }
    }
}
